// import { THREE, OrbitControls, occtimportjs } from "../plugins/js";
import { useCallback, useEffect, useRef, useState } from "react"
import *  as THREE from "three"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"
import Worker from "./myWorker?worker"
import styles from "./App.module.less"
import { BuildMesh } from "./config"
function App() {
  const [filePath, setFilePath] = useState("")
  const [loading, setLoading] = useState(false)
  const [isFinilsh, setIsFinilsh]=useState(false)
  const canvasRef = useRef<HTMLDivElement>(null)
  const myWorker = useRef<Worker>(null)

  const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target || !e.target.files || !myWorker.current || !canvasRef.current) return
    const file = e.target.files[0];
    if (file) {
      const blob = new Blob([file])
      const url = URL.createObjectURL(blob)
      setFilePath(url)
    setLoading(true)
    }
  }, [canvasRef, myWorker])
  const renderCanvas = useCallback((StpData: THREE.Object3D<THREE.Object3DEventMap>) => {
    if (!myWorker.current || !canvasRef.current) return
    const scene = new THREE.Scene()
    const render = new THREE.WebGLRenderer({
      antialias: true,
    })
    const camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.1, 5000)
    const controls = new OrbitControls(camera, render.domElement)
    	scene.background = new THREE.Color(0xa0a0a0);
   camera.position.set(30, 10, 500);
    render.setSize(window.innerWidth, window.innerHeight)
    canvasRef.current.appendChild(render.domElement)

    	const light = new THREE.AmbientLight(0xffffff, 3); 
    light.castShadow = false
    scene.add(light)
    	const directionalLight = new THREE.DirectionalLight(0xffffff, 3);
				directionalLight.position.set(5, 5, 5).normalize();
				directionalLight.castShadow = false;
    // 添加四个方向的平行光（无阴影）
    const lightIntensity = 2;
    const positions = [
      [5, 5, 5],   // 右上前方
      [-5, 5, -5], // 左后上方
      [5, -5, -5], // 右下后方
      [-5, -5, 5]  // 左前下方
    ];
    positions.forEach(pos => {
      const light = new THREE.DirectionalLight(0xffffff, lightIntensity);
      light.position.set(pos[0], pos[1], pos[2]);
      light.castShadow = false; 
      scene.add(light);
    });
    controls.enablePan = true;
    controls.enableZoom = true;
    controls.enableRotate = true;
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    camera.position.z = 5;
    scene.add(StpData)
    const boundingBox = new THREE.Box3().setFromObject(StpData)
    const size = boundingBox.getSize(new THREE.Vector3()).length()
    const scaleFactor=(Math.min(window.innerWidth,window.innerHeight) / size) * 0.005
    StpData.scale.set(scaleFactor, scaleFactor, scaleFactor)
    setLoading(false)
    setIsFinilsh(true)
    window.addEventListener('resize', onWindowResize, false);

    function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      render.setSize(window.innerWidth, window.innerHeight);
    }

    // 渲染循环
    const animate = function () {
      requestAnimationFrame(animate);
      controls.update();
      render.render(scene, camera);
    };
    animate();
  }, [myWorker, canvasRef])
  useEffect(() => {
    if (!filePath || !myWorker.current) return
    myWorker.current.postMessage({
      filePath
    })
  }, [filePath, myWorker])
  useEffect(() => {
    const _work = new Worker()
    _work.onmessage = ({ data }) => {
      const geometry = data.data
      const Object3D = new THREE.Object3D()
      const group = new THREE.Group()
      for (const resultMesh of geometry.meshes) {
        const { mesh, edges } = BuildMesh(resultMesh, true)
        group.add(mesh)
        if (edges) group.add(edges)
      }
      Object3D.add(group)
      renderCanvas(Object3D)
    }
    myWorker.current = _work
  }, [])

  return <div ref={canvasRef} className={styles.container}>
  {( !loading && !isFinilsh ) && <div className={styles.file}>
    <input onChange={onChange} type="file" name="file" id="" />
    </div>}
    {loading && <div className={styles.loading}>模型加载中........</div>}

  </div>;
}

export default App;
